<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 步骤状态
const currentStep = ref(1)
const totalSteps = 3

// 表单数据
const formData = reactive({
  phone: '',
  verificationCode: '',
  securityAnswers: [] as string[],
  newPassword: '',
  confirmPassword: '',
  userId: null as number | null
})

// 安全问题列表
const securityQuestions = ref<{questionId: number, question: string}[]>([])

// 界面状态
const uiState = reactive({
  isSubmitting: false,
  errorMessage: '',
  passwordStrength: 0,
  showNewPassword: false, // 新增：显示新密码
  showConfirmPassword: false // 新增：显示确认密码
})

// 更新步骤
const updateStep = (step: number) => {
  currentStep.value = step
}

// 验证手机号和验证码
const verifyPhoneAndCode = async () => {
  if (!formData.phone || !/^1[3-9]\d{9}$/.test(formData.phone)) {
    ElMessage.error('请输入正确的手机号码')
    return
  }

  if (!formData.verificationCode) {
    ElMessage.error('请输入验证码')
    return
  }

  // 使用固定验证码123456进行验证
  if (formData.verificationCode !== '123456') {
    ElMessage.error('验证码错误，请输入123456')
    return
  }

  uiState.isSubmitting = true
  try {
    // 获取用户ID
    const userResponse = await fetch(`/api/users/selIdByPhoneOrNickname?account=${formData.phone}`)
    const userResult = await userResponse.json()

    if (userResult.code !== 200) {
      ElMessage.error('用户不存在')
      return
    }

    const userId = userResult.data
    formData.userId = userId // 保存用户ID用于后续步骤

    // 获取安全问题
    const questionsResponse = await fetch(`/api/securityQuestions/selQuestions?userId=${userId}`)
    const questionsResult = await questionsResponse.json()

    if (questionsResult.code === 200 && questionsResult.data && questionsResult.data.length > 0) {
      // 正确解析安全问题数据
      securityQuestions.value = questionsResult.data.map((q: any) => ({
        questionId: q.questionId,
        question: q.question
      }))
      formData.securityAnswers = new Array(securityQuestions.value.length).fill('')
      updateStep(2)
    } else {
      ElMessage.error('未设置安全问题，请联系管理员')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    uiState.isSubmitting = false
  }
}

// 验证安全问题
const verifySecurityAnswers = async () => {
  if (formData.securityAnswers.some(answer => !answer.trim())) {
    ElMessage.error('请完整回答所有安全问题')
    return
  }

  if (!formData.userId) {
    ElMessage.error('用户信息丢失，请重新开始')
    return
  }

  uiState.isSubmitting = true
  try {
    // 准备验证数据
    const verifyData = {
      userId: formData.userId,
      answers: securityQuestions.value.map((question, index) => ({
        questionId: question.questionId,
        answer: formData.securityAnswers[index]
      }))
    }

    // 调用后端API验证安全问题答案
    const verifyResponse = await fetch('/api/securityQuestions/verifyAnswers', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(verifyData)
    })

    const verifyResult = await verifyResponse.json()

    if (verifyResult.code === 200) {
      updateStep(3)
    } else {
      ElMessage.error('安全问题答案不正确：' + (verifyResult.msg || '验证失败'))
    }
  } catch (error) {
    ElMessage.error('验证失败，请稍后重试')
  } finally {
    uiState.isSubmitting = false
  }
}

// 密码强度检测
const checkPasswordStrength = (password: string) => {
  let strength = 0
  if (password.length >= 8) strength += 1
  if (/[A-Z]/.test(password)) strength += 1
  if (/[0-9]/.test(password)) strength += 1
  if (/[^A-Za-z0-9]/.test(password)) strength += 1
  uiState.passwordStrength = strength
}

// 切换密码显示状态
const togglePasswordVisibility = (field: 'newPassword' | 'confirmPassword') => {
  if (field === 'newPassword') {
    uiState.showNewPassword = !uiState.showNewPassword
  } else {
    uiState.showConfirmPassword = !uiState.showConfirmPassword
  }
}

// 获取密码强度文本
const getPasswordStrengthText = () => {
  switch (uiState.passwordStrength) {
    case 0:
    case 1:
      return { text: '弱', color: '#e74a3b' }
    case 2:
    case 3:
      return { text: '中', color: '#f6c23e' }
    case 4:
      return { text: '强', color: '#1cc88a' }
    default:
      return { text: '弱', color: '#e74a3b' }
  }
}

// 重置密码
const resetPassword = async () => {
  if (formData.newPassword !== formData.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }

  if (formData.newPassword.length < 8) {
    ElMessage.error('密码长度不能少于8位')
    return
  }

  if (!/(?=.*[A-Za-z])(?=.*\d)/.test(formData.newPassword)) {
    ElMessage.error('密码需包含字母和数字')
    return
  }

  if (!formData.userId) {
    ElMessage.error('用户信息丢失，请重新开始')
    return
  }

  uiState.isSubmitting = true
  try {
    // 调用后端API重置密码
    const resetResponse = await fetch('/api/users/revise', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        userId: formData.userId,
        originalpwd: formData.newPassword
      })
    })

    const resetResult = await resetResponse.json()

    if (resetResult.code === 200) {
      ElMessage.success('密码重置成功！')
      setTimeout(() => {
        router.push('/start')
      }, 1500)
    } else {
      ElMessage.error('密码重置失败：' + resetResult.msg)
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    uiState.isSubmitting = false
  }
}

// 上一步
const goBack = () => {
  if (currentStep.value > 1) {
    currentStep.value--
  } else {
    backToLogin()
  }
}

// 返回登录页面
const backToLogin = () => {
  router.push('/login')
}

// 重置表单
const resetForm = () => {
  formData.phone = ''
  formData.verificationCode = ''
  formData.securityAnswers = []
  formData.newPassword = ''
  formData.confirmPassword = ''
  formData.userId = null
  securityQuestions.value = []
  currentStep.value = 1
  uiState.showNewPassword = false
  uiState.showConfirmPassword = false
  uiState.passwordStrength = 0
}
</script>

<template>
  <div class="page-container">
    <div class="forgot-password-container">
      <div class="header-section">
        <h2 class="form-title">找回密码</h2>
        <div class="title-divider"></div>
      </div>

      <!-- 步骤指示器 -->
      <div class="step-indicator">
        <div class="step" :class="{ active: currentStep >= 1, completed: currentStep > 1 }">
          <span class="step-number">1</span>
          <span class="step-label">验证身份</span>
        </div>
        <div class="step" :class="{ active: currentStep >= 2, completed: currentStep > 2 }">
          <span class="step-number">2</span>
          <span class="step-label">安全问题</span>
        </div>
        <div class="step" :class="{ active: currentStep >= 3 }">
          <span class="step-number">3</span>
          <span class="step-label">重置密码</span>
        </div>
        <div class="step-line">
          <div class="step-line-progress" :style="{ width: `${((currentStep - 1) / (totalSteps - 1)) * 100}%` }"></div>
        </div>
      </div>

      <!-- 第一步：验证身份 -->
      <div v-if="currentStep === 1" class="form-section">
        <div class="form-title">请输入您的手机号</div>

        <div class="form-group">
          <label for="phone">
            <i class="icon">📱</i> 手机号
          </label>
          <input
              id="phone"
              v-model="formData.phone"
              type="tel"
              placeholder="请输入注册时使用的手机号"
              required
          />
        </div>

        <div class="form-group">
          <label for="verificationCode">
            <i class="icon">🔒</i> 验证码
          </label>
          <div class="input-with-icon">
            <input
                id="verificationCode"
                v-model="formData.verificationCode"
                type="text"
                placeholder="请输入验证码：123456"
                required
            />
            <div class="verification-hint">
              演示验证码：<strong>123456</strong>
            </div>
          </div>
        </div>

        <div class="btn-container">
          <button
              type="button"
              class="verify-btn"
              :disabled="uiState.isSubmitting"
              @click="verifyPhoneAndCode"
          >
            {{ uiState.isSubmitting ? '验证中...' : '下一步' }}
          </button>
        </div>
      </div>

      <!-- 第二步：安全问题 -->
      <div v-else-if="currentStep === 2" class="form-section">
        <div class="form-title">请回答安全问题</div>

        <div class="security-questions">
          <div class="security-title">请回答以下安全问题以验证您的身份</div>

          <div v-for="(question, index) in securityQuestions" :key="question.questionId" class="form-group">
            <label :for="`answer-${index}`">
              <i class="icon">❓</i> 问题 {{ index + 1 }}
            </label>
            <div class="security-question">
              <p class="question-text">{{ question.question }}</p>
              <input
                  :id="`answer-${index}`"
                  v-model="formData.securityAnswers[index]"
                  type="text"
                  :placeholder="`请输入问题${index + 1}的答案`"
                  required
              />
            </div>
          </div>
        </div>

        <div class="form-actions">
          <button type="button" class="secondary-btn" @click="goBack">
            上一步
          </button>
          <button
              type="button"
              class="submit-btn"
              :disabled="uiState.isSubmitting"
              @click="verifySecurityAnswers"
          >
            {{ uiState.isSubmitting ? '验证中...' : '下一步' }}
          </button>
        </div>
      </div>

      <!-- 第三步：重置密码 -->
      <div v-else-if="currentStep === 3" class="form-section">
        <div class="form-title">请设置新密码</div>

        <div class="form-group">
          <label for="newPassword">
            <i class="icon">🔒</i> 新密码
          </label>
          <div class="password-input-container">
            <input
                id="newPassword"
                v-model="formData.newPassword"
                :type="uiState.showNewPassword ? 'text' : 'password'"
                placeholder="请设置新密码（至少8位，包含字母和数字）"
                required
                @input="checkPasswordStrength(formData.newPassword)"
            />
            <button
                type="button"
                class="password-toggle"
                @click="togglePasswordVisibility('newPassword')"
                :aria-label="uiState.showNewPassword ? '隐藏密码' : '显示密码'"
            >
              <i class="icon">{{ uiState.showNewPassword ? '👁️' : '👁️‍🗨️' }}</i>
            </button>
          </div>
          <div class="password-rules">密码需包含字母和数字，长度至少8位</div>
          <div class="password-strength-container">
            <div class="password-strength">
              <div
                  class="password-strength-bar"
                  :class="{
                  'strength-weak': uiState.passwordStrength <= 1,
                  'strength-medium': uiState.passwordStrength > 1 && uiState.passwordStrength <= 3,
                  'strength-strong': uiState.passwordStrength > 3
                }"
                  :style="{ width: `${uiState.passwordStrength * 25}%` }"
              ></div>
            </div>
            <div class="password-strength-text" :style="{ color: getPasswordStrengthText().color }">
              强度：{{ getPasswordStrengthText().text }}
            </div>
          </div>
        </div>

        <div class="form-group">
          <label for="confirmPassword">
            <i class="icon">🔒</i> 确认密码
          </label>
          <div class="password-input-container">
            <input
                id="confirmPassword"
                v-model="formData.confirmPassword"
                :type="uiState.showConfirmPassword ? 'text' : 'password'"
                placeholder="请再次输入新密码"
                required
            />
            <button
                type="button"
                class="password-toggle"
                @click="togglePasswordVisibility('confirmPassword')"
                :aria-label="uiState.showConfirmPassword ? '隐藏密码' : '显示密码'"
            >
              <i class="icon">{{ uiState.showConfirmPassword ? '👁️' : '👁️‍🗨️' }}</i>
            </button>
          </div>
        </div>

        <div class="form-actions">
          <button type="button" class="secondary-btn" @click="goBack">
            上一步
          </button>
          <button
              type="button"
              class="submit-btn"
              :disabled="uiState.isSubmitting"
              @click="resetPassword"
          >
            {{ uiState.isSubmitting ? '重置中...' : '确认重置' }}
          </button>
        </div>
      </div>

      <p class="form-footer">
        <a href="#" @click.prevent="backToLogin" class="footer-link">返回登录</a>
      </p>
    </div>
  </div>
</template>

<style scoped>
/* 原有样式保持不变，新增以下样式 */

.password-input-container {
  position: relative;
  display: flex;
  align-items: center;
}

.password-toggle {
  position: absolute;
  right: 8px;
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.password-toggle:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.password-toggle .icon {
  font-size: 1.2rem;
  font-style: normal;
}

.password-strength-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 0.5rem;
}

.password-strength {
  flex: 1;
  height: 5px;
  background: #eee;
  border-radius: 3px;
  overflow: hidden;
}

.password-strength-bar {
  height: 100%;
  transition: width 0.3s ease, background-color 0.3s ease;
}

.strength-weak {
  background: #e74a3b;
}

.strength-medium {
  background: #f6c23e;
}

.strength-strong {
  background: #1cc88a;
}

.password-strength-text {
  font-size: 0.8rem;
  font-weight: 500;
  min-width: 60px;
  text-align: right;
}

/* 调整密码输入框的右边距，为切换按钮留出空间 */
.password-input-container input {
  padding-right: 40px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .password-strength-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }

  .password-strength-text {
    align-self: flex-end;
  }
}

@media (max-width: 480px) {
  .password-toggle {
    right: 6px;
    padding: 3px;
  }

  .password-toggle .icon {
    font-size: 1.1rem;
  }

  .password-input-container input {
    padding-right: 35px;
  }
}

.page-container {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  min-height: 100vh;
  padding: 0.8rem;
  background-color: #f8f9fa;
}

.forgot-password-container {
  width: 100%;
  max-width: 500px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  padding: 1.5rem;
}

.header-section {
  text-align: center;
  margin-bottom: 1.2rem;
}

.form-title {
  color: #2a4b8c;
  font-size: 1.6rem;
  margin-bottom: 0.5rem;
  font-weight: 600;
}

.title-divider {
  width: 50px;
  height: 2px;
  background: rgba(42, 75, 140, 0.3);
  margin: 0.3rem auto;
  border-radius: 2px;
}

.step-indicator {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2rem;
  position: relative;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 2;
  position: relative;
}

.step-number {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #999;
  transition: all 0.3s ease;
}

.step.active .step-number {
  background: #2a4b8c;
  color: white;
  box-shadow: 0 0 0 4px rgba(42, 75, 140, 0.2);
}

.step.completed .step-number {
  background: #1cc88a;
  color: white;
}

.step-label {
  font-size: 12px;
  color: #999;
  margin-top: 0.5rem;
  white-space: nowrap;
}

.step.active .step-label {
  color: #2a4b8c;
  font-weight: 500;
}

.step-line {
  position: absolute;
  top: 18px;
  left: 18px;
  right: 18px;
  height: 2px;
  background: #f0f0f0;
  z-index: 1;
}

.step-line-progress {
  height: 100%;
  background: #2a4b8c;
  transition: width 0.5s ease;
}

.form-section {
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  margin-bottom: 1.5rem;
}

label {
  color: #555;
  font-size: 0.9rem;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 0.4rem;
}

.icon {
  font-size: 1rem;
}

.input-with-icon {
  position: relative;
  display: flex;
  align-items: center;
}

.verification-hint {
  position: absolute;
  right: 8px;
  padding: 0.4rem 0.8rem;
  font-size: 0.8rem;
  color: #2a4b8c;
  background: rgba(42, 75, 140, 0.1);
  border-radius: 4px;
}

input {
  width: 100%;
  padding: 0.7rem;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 0.9rem;
  transition: all 0.2s ease;
  background-color: #f8f9fa;
}

input:focus {
  outline: none;
  border-color: #2a4b8c;
  box-shadow: 0 0 0 2px rgba(42, 75, 140, 0.1);
  background-color: #fff;
}

.password-rules {
  font-size: 0.8rem;
  color: #777;
  margin-top: 0.3rem;
}

.password-strength {
  height: 5px;
  background: #eee;
  border-radius: 3px;
  margin-top: 0.5rem;
  overflow: hidden;
}

.password-strength-bar {
  height: 100%;
  transition: width 0.3s ease;
}

.strength-weak {
  background: #e74a3b;
}

.strength-medium {
  background: #f6c23e;
}

.strength-strong {
  background: #1cc88a;
}

.btn-container {
  display: flex;
  justify-content: center;
  margin-top: 1rem;
}

.verify-btn,
.submit-btn,
.secondary-btn {
  padding: 0.8rem 1.8rem;
  border: none;
  border-radius: 8px;
  font-size: 0.95rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.verify-btn,
.submit-btn {
  background: linear-gradient(to right, #2a4b8c, #3a6bc5);
  color: white;
}

.verify-btn:hover:not(:disabled),
.submit-btn:hover:not(:disabled) {
  background: linear-gradient(to right, #3a6bc5, #2a4b8c);
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(42, 75, 140, 0.3);
}

.secondary-btn {
  background: #f0f0f0;
  color: #666;
}

.secondary-btn:hover:not(:disabled) {
  background: #e0e0e0;
  transform: translateY(-1px);
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.form-actions {
  display: flex;
  gap: 0.8rem;
  justify-content: center;
  margin-top: 1rem;
}

.form-actions .secondary-btn,
.form-actions .submit-btn {
  flex: 1;
  max-width: 160px;
}

.form-footer {
  color: #666;
  text-align: center;
  margin-top: 1.5rem;
  font-size: 0.85rem;
}

.footer-link {
  color: #2a4b8c;
  text-decoration: none;
  font-weight: 500;
}

.footer-link:hover {
  text-decoration: underline;
}

.security-questions {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 1rem;
  background: #f9fafc;
  margin-bottom: 1rem;
}

.security-title {
  font-size: 0.9rem;
  margin-bottom: 1rem;
  color: #555;
  font-weight: 500;
}

.security-question {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
}

.question-text {
  color: #666;
  font-size: 0.85rem;
  margin: 0;
  padding-left: 0.4rem;
  border-left: 2px solid #2a4b8c;
}

@media (max-width: 768px) {
  .forgot-password-container {
    padding: 1.2rem;
  }

  .form-title {
    font-size: 1.4rem;
  }

  .step-indicator {
    margin-bottom: 1.5rem;
  }

  .step-number {
    width: 32px;
    height: 32px;
    font-size: 14px;
  }

  .step-label {
    font-size: 11px;
  }

  input {
    padding: 0.6rem;
  }

  .verify-btn,
  .submit-btn,
  .secondary-btn {
    padding: 0.7rem 1.5rem;
    font-size: 0.9rem;
  }

  .form-actions {
    flex-direction: column;
    gap: 0.5rem;
    align-items: center;
  }

  .form-actions .secondary-btn,
  .form-actions .submit-btn {
    width: 100%;
    max-width: 100%;
  }
}

@media (max-width: 480px) {
  .forgot-password-container {
    padding: 1rem;
  }

  .form-title {
    font-size: 1.3rem;
  }

  .verify-btn,
  .submit-btn,
  .secondary-btn {
    padding: 0.6rem 1.2rem;
    font-size: 0.85rem;
  }

  .verification-hint {
    font-size: 0.7rem;
    padding: 0.3rem 0.6rem;
  }
}
</style>